package com.alan.netty.test;

import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author weiBin
 * @date 2018/11/19
 */
public class BeanMain2 {
    public static void main(String[] args) {
        Bean a1 = new Bean("2,3", "1", "test1");
        Bean a2 = new Bean("4", "2", "test2");
        Bean a3 = new Bean("4", "3", "test3");
        Bean a4 = new Bean("5", "4", "test4");

        Bean a12 = new Bean("7", "6", "test2");
        Bean a13 = new Bean("8", "7", "test3");
        Bean a14 = new Bean("9", "8", "test4");
        List<Bean> list = new ArrayList<>();
        list.add(a1);
        list.add(a2);
        list.add(a3);
        list.add(a4);
        list.add(a12);
        list.add(a13);
        list.add(a14);
        reorder(list);
    }

    private static List<Bean> getNonFollow(List<Bean> list) throws RuntimeException {
        List<Bean> result = new ArrayList<>();
        for (Bean bean : list) {
            String follow = bean.getFollowIds();
            if (StringUtils.isEmpty(follow)) {
                result.add(bean);
            } else {
                follow = "," + follow + ",";
                String finalFollow = follow;
                if (list.stream().filter(e -> finalFollow.contains("," + e.getId() + ",")).count() > 0) {
                    continue;
                } else {
                    result.add(bean);
                }
            }
        }
        return result;
    }

    private static List<List<Bean>> reorder(List<Bean> list) throws RuntimeException {
        List<List<Bean>> result = new ArrayList<>();
        while (list.size() > 0) {
            List<Bean> temp = getNonFollow(list);
            list.removeAll(temp);
            result.add(temp);
        }
        for (int i = 0; i < result.size(); i++) {
            for (Bean temp : result.get(i)) {
                System.out.println(String.format("%s: Bean id is %s", i + 1, temp.getId()));
            }
        }
        return result;
    }
}
